# PowerShell 部署脚本

param(
    [switch]$WithNginx,
    [switch]$Clean,
    [switch]$ShowLogs
)

Write-Host "🚀 WebRTC 项目 Docker 部署脚本" -ForegroundColor Cyan
Write-Host "================================" -ForegroundColor Cyan

# 检查 Docker 是否安装
try {
    $dockerVersion = docker --version
    Write-Host "✅ Docker 已安装: $dockerVersion" -ForegroundColor Green
} catch {
    Write-Host "❌ Docker 未安装，请先安装 Docker Desktop" -ForegroundColor Red
    exit 1
}

try {
    $composeVersion = docker-compose --version
    Write-Host "✅ Docker Compose 已安装: $composeVersion" -ForegroundColor Green
} catch {
    Write-Host "❌ Docker Compose 未安装" -ForegroundColor Red
    exit 1
}

# 停止现有容器
Write-Host "🛑 停止现有容器..." -ForegroundColor Yellow
try {
    docker-compose down --remove-orphans
} catch {
    Write-Host "没有运行中的容器" -ForegroundColor Gray
}

# 清理旧镜像（可选）
if ($Clean) {
    Write-Host "🗑️ 清理旧镜像..." -ForegroundColor Yellow
    docker system prune -f
    docker image prune -f
}

# 生成 SSL 证书
Write-Host "🔐 检查 SSL 证书..." -ForegroundColor Yellow
if (-not (Test-Path "nginx\ssl\cert.pem")) {
    Write-Host "生成 SSL 证书..." -ForegroundColor Yellow
    & .\scripts\generate-certs.ps1
} else {
    Write-Host "证书已存在，跳过生成" -ForegroundColor Gray
}

# 构建镜像
Write-Host "🔨 构建 Docker 镜像..." -ForegroundColor Yellow
docker-compose build --no-cache

if ($LASTEXITCODE -ne 0) {
    Write-Host "❌ 镜像构建失败" -ForegroundColor Red
    exit 1
}

# 启动服务
if ($WithNginx) {
    Write-Host "🚀 启动应用 + Nginx..." -ForegroundColor Green
    docker-compose --profile with-nginx up -d
    
    if ($LASTEXITCODE -eq 0) {
        Write-Host "✅ 部署完成！" -ForegroundColor Green
        Write-Host "🌐 访问地址: https://localhost" -ForegroundColor Cyan
        Write-Host "📊 健康检查: https://localhost/health" -ForegroundColor Cyan
    }
} else {
    Write-Host "🚀 启动应用服务..." -ForegroundColor Green
    docker-compose up -d
    
    if ($LASTEXITCODE -eq 0) {
        Write-Host "✅ 部署完成！" -ForegroundColor Green
        Write-Host "🌐 访问地址: https://localhost:5001" -ForegroundColor Cyan
        Write-Host "📊 健康检查: https://localhost:5001/health" -ForegroundColor Cyan
    }
}

# 显示容器状态
Write-Host ""
Write-Host "📋 容器状态:" -ForegroundColor Yellow
docker-compose ps

# 显示日志
if ($ShowLogs) {
    Write-Host ""
    Write-Host "📝 实时日志 (Ctrl+C 退出):" -ForegroundColor Yellow
    docker-compose logs -f
}

Write-Host ""
Write-Host "💡 使用提示:" -ForegroundColor Yellow
Write-Host "  查看日志: docker-compose logs -f" -ForegroundColor Gray
Write-Host "  停止服务: docker-compose down" -ForegroundColor Gray
Write-Host "  重启服务: docker-compose restart" -ForegroundColor Gray 